package hibatis.support.parse;


import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by huangdachao on 2018/6/18 01:25.
 */
public class ViewMeta {
    private EntityMeta em;
    private Set<String> views;
    private Set<Table> tables = new HashSet<>();
    private List<JoinMeta> joinMeta = new ArrayList<>();
    private Set<TableColumn> columns = new HashSet<>();
    private Map<TableColumn, String> columnMap = new HashMap<>();

    private ViewMeta() { }

    public static ViewMeta parse(EntityMeta em, String[] views) {
        ViewMeta vm = new ViewMeta();
        vm.em = em;
        vm.views = new HashSet<>(Arrays.asList(views));
        vm.tables.add(em.getTable());

        em.getFieldMeta().values().forEach(fm -> {
            if (fm.getViews().isEmpty() || contains(vm.views, fm.getViews())) {
                vm.columns.add(fm.getTableColumn());
                vm.columnMap.put(fm.getTableColumn(), fm.getField().getName());
                vm.tables.add(fm.getTableColumn().toTable());
            }
        });

        vm.joinMeta = em.getJoinMap().values().stream()
            .filter(m -> vm.tables.contains(m.getTable()))
            .collect(Collectors.toList());
        return vm;
    }

    public EntityMeta getEntityMeta() {
        return em;
    }

    public Set<Table> getTables() {
        return tables;
    }

    public List<JoinMeta> getJoinMeta() {
        return joinMeta;
    }

    public Set<TableColumn> getColumns() {
        return columns;
    }

    public Map<TableColumn, String> getColumnMap() {
        return columnMap;
    }

    public String getField(TableColumn tc) {
        return columnMap.get(tc);
    }

    private static boolean contains(Set<String> views, List<String> list) {
        for (String v : list) {
            if (views.contains(v)) {
                return true;
            }
        }
        return false;
    }
}
